from django.shortcuts import render, redirect, HttpResponse
from django.contrib import auth
from django.contrib.auth.decorators import login_required, REDIRECT_FIELD_NAME
from api.utils.common import MyResponse
from django.http import JsonResponse
from io import BytesIO
from api.utils import common, myform
from api import models
from PIL import Image, ImageDraw, ImageFont
import random


# Create your views here.

def login(request):
    response = MyResponse()
    if request.method == 'POST':
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        validCode = request.POST.get('validCode')
        ve_code = request.session['ve_code']
        print(ve_code)
        user = auth.authenticate(username=name, password=pwd)
        if ve_code.upper() == validCode.upper():
            if user:
                response.name = name
                response.user_type =  user.user_type
                response.msg = '登陆成功'
                auth.login(request, user)
            else:
                response.status = 200
                response.msg = '用户名或密码错误'
        else:
            response.status = 200
            response.msg = '验证码错误'
        return JsonResponse(response.get_dic)
    return render(request, 'login.html', locals())


@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def logout(request):
    auth.logout(request)
    print(1)
    return redirect('/index/')


def get_validCode(request):
    num = len(request.META.get('QUERY_STRING'))
    img = Image.new('RGB', (200, 35), color=common.get_color())
    img_draw = ImageDraw.Draw(img)
    font = ImageFont.truetype('static/font/ss.ttf', size=30)
    ve_code = ''
    for i in range(5):
        number = random.randint(0, 9)
        upper = chr(random.randint(97, 122))
        lower = chr(random.randint(65, 90))
        add = str(random.choice((number, upper, lower)))
        ve_code += add
        img_draw.text((i * 30 + 30, 0), add, common.get_color(), font)
    request.session['ve_code'] = ve_code

    # 噪线
    for i in range(5):
        x1 = random.randint(0, 200)
        x2 = random.randint(0, 200)
        y1 = random.randint(0, 35)
        y2 = random.randint(0, 35)
        img_draw.line((x1, y1, x2, y2), fill=common.get_color())
    # 噪点
    if num == 0: num = 1
    if num > 3: num = 3
    print(num)
    for i in range(100 - num * 20):
        img_draw.point([random.randint(0, 200), random.randint(0, 35)], fill=common.get_color())
        x = random.randint(0, 200)
        y = random.randint(0, 35)
        img_draw.arc((x, y, x + 4, y + 4), 0, 90, fill=common.get_color())

    f = BytesIO()
    img.save(f, 'png')
    data = f.getvalue()
    return HttpResponse(data)


@login_required(redirect_field_name=REDIRECT_FIELD_NAME, login_url='/login/')
def change_pwd(request):
    response = {'status': 200, 'error': None}
    if request.method == 'POST':
        user = request.user
        data = myform.Change_Password(request.POST)
        if data.is_valid():
            old_pwd = data.cleaned_data.get('old_password')
            re_pwd = data.cleaned_data.get('password')
            if user.check_password(old_pwd):
                user.set_password(re_pwd)
                user.save()
            else:
                response['status'] = 402
        else:
            response['status'] = 401
            response['error'] = data.errors
        return JsonResponse(response)
    data = myform.Change_Password()
    return render(request, 'change_pwd.html', locals())
